<template>
  <div>
    <a-row>
      <a-col :xs="{ span: 24 }" :lg="{ span: 2 }">
        <a-select
          style="width: 150px; margin-bottom: 20px"
          placeholder="请选择文章分类"
          @change="
            (value) => {
              this.article.category = value;
            }
          "
          v-model="article.category"
        >
          <a-select-option
            :value="item.id"
            v-for="item in categoryList"
            :key="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col
        :lg="{ span: 2, offset: 1 }"
        :xs="{ span: 24 }"
        style="margin-bottom: 10px"
      >
        <a-space align="center">
          <span>置顶文章</span>
          <a-switch
            @change="changeSwitch"
            v-model="article.isTop == 1 ? true : false"
          />
        </a-space>
      </a-col>
      <a-col :lg="{ span: 4, offset: 3 }" :xs="{ span: 24 }">
        <a-input
          addon-before="文章标题"
          placeholder="请输入文章标题"
          v-model="article.title"
        />
      </a-col>
    </a-row>

    <quill-editor
      v-model="article.content"
      class="editor"
      :options="editorOption"
      ref="myQuillEditor"
    >
    </quill-editor>

    <a-space :style="{ marginTop: '50px' }">
      <a-button @click="preview()" size="large">预览</a-button>
      <a-button type="primary" size="large" @click="submit()">发表</a-button>
    </a-space>
    <a-modal
      title="文章预览"
      :dialog-style="{ top: '20px' }"
      :visible="previewArticleVisible"
      @ok="previewArticleVisible = false"
      @cancel="previewArticleVisible = false"
    >
      <div v-html="article.content"></div>
    </a-modal>
    <a-upload list-type="picture" v-show="false" :customRequest="uploadimg">
      <a-button> <a-icon type="upload" /> upload </a-button>
    </a-upload>
  </div>
</template>

<script>
export default {
  async mounted() {
    this.getCategoryList();
    // 判断是否修改文章信息
    if (this.$route.name === "articleEdit") {
      this.getArticleDetail(this.$route.params.id);
      this.mode = "edit";
    }
    this.$bus.$emit("setUserInfo", info);
  },
  data() {
    return {
      article: {
        title: "",
        content: "",
        category: "",
        isTop: 0,
      },
      previewArticleVisible: false,
      // 分类列表
      categoryList: [],
      editorOption: {
        //由于需要重写tabbar 中header图片的上传事件，图片重写又在tabbar中，没办法只能重新定义工具栏
        modules: {
          toolbar: {
            container: [
              // 工具栏配置
              ["bold"],
              ["italic"],
              ["underline"],
              ["strike"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ align: [] }],
              [{ header: [1, 2, 3, 4, 5, 6, !1] }],
              ["blockquote"],
              ["code-block"], //不需要的可以干掉
              ["image"],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ direction: "rtl" }],
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  // 获取到antd的upload框选择图片的弹出框事件并触发一次点击
                  document.querySelector(".ant-upload .ant-btn").click();
                } else {
                  //禁用quill自带的image时间
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      // 预加载文章信息
      preArticle: {},
      // 编辑 或 发布
      mode: "add",
    };
  },
  methods: {
    // 发布文章
    submit() {
      if (!this.article.title) {
        this.$message.error("请输入文章标题");
        return;
      }
      if (!this.article.content) {
        this.$message.error("请输入文章内容");
        return;
      }
      if (!this.article.category) {
        this.$message.error("请选择文章分类");
        return;
      }
      this.$axios
        .post(`/api/article/${this.mode}.php`, this.article)
        .then((res) => {
          console.log(res);
          if (res.data.code === 1) {
            this.$message.success("发布成功");
            this.$router.push("/admin/articleList");
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    // 文章预览
    preview() {
      if (this.article.content.trim() == "")
        return this.$message.info("请输入内容后预览");
      this.previewArticleVisible = true;
    },
    // 获取所有分类
    getCategoryList() {
      this.$axios.get("/api/category/list.php").then((res) => {
        const { data } = res;
        if (data.code === 1) {
          const arr = data.data.map((item) => {
            return {
              id: item[0],
              name: item[1],
            };
          });
          this.categoryList = arr;
        } else {
          this.$message.error("获取分类失败!");
        }
      });
    },
    // 上传图片
    uploadimg(file) {
      const reader = new FileReader();
      reader.readAsDataURL(file.file); // 读取图片文件

      reader.onload = (file) => {
        const params = {
          myBase64: file.target.result, // 把 本地图片的base64编码传给后台，调接口，生成图片的url
        };
        this.$axios.post("/api/upload/upload.php", params).then((res) => {
          console.log(res);
          let quill = this.$refs.myQuillEditor.quill;

          // 获取光标所在位置
          let length = quill.getSelection().index;
          if (res) {
            console.log(length);
            // 插入图片  res为服务器返回的图片地址
            quill.insertEmbed(
              length,
              "image",
              this.imgUrl + res.data.data.src,
              {
                // 设置图片宽度
                width: "100px",
              }
            );
            // 调整光标到最后
            quill.setSelection(length + 1);
            this.$message.success("上传成功");
          } else if (res.file.status === "error") {
            this.$message.error("图片插入失败");
          }
        });
      };
    },
    // 获取文章详情
    getArticleDetail(id) {
      this.$axios
        .post(`/api/article/detail.php`, {
          id,
        })
        .then((res) => {
          if (res.data.code === 1) {
            const { title, content, category_id, isTop } = res.data.data[0];
            this.article = {
              title,
              content,
              category: category_id,
              isTop,
              id,
            };
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 改变开关切换
    changeSwitch() {
      this.article.isTop = this.article.isTop ? 0 : 1;
    },
  },
};
</script>
